package com.xcalendar.servlets;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.KeyFactory;
import com.xcalendar.c2dm.C2DMManager;
import com.xcalendar.constant.XConstants;
import com.xcalendar.database.dao.LocationDAO;
import com.xcalendar.database.table.Event;
import com.xcalendar.database.table.User;
import com.xcalendar.exception.IncorrectNameOrPasswordException;
import com.xcalendar.management.EventManager;
import com.xcalendar.management.UserManager;
import com.xcalendar.managementImpl.EventManagerImpl;
import com.xcalendar.managementImpl.UserManagerImpl;
import com.xcalendar.service.rest.converter.EventConverter;

@SuppressWarnings("serial")
public class AddEventController extends HttpServlet {
	public static String ClientLoginURL = "https://www.google.com/accounts/ClientLogin";
	public static String AuthTokenParams = "accountType=HOSTED_OR_GOOGLE&Email=lixiaoyi.efrei@gmail.com&Passwd=898725222&service=ac2dm&source=bupt-c2dmdemo-1.0";
	public static String C2DMServerURL = "http://android.apis.google.com/c2dm/send";
	//public static String Registration_ID = "APA91bGvWFVGiy93W9R8yX9loFr0ycyzzYQoWGbYJGtSB_bH8Cd1V7-ij8opk2Bm1WEnjkiqXD1-lY3SwRxtoTlHg38ZwfqboU7nCDwQmKz6s1HztbcGmqn_zlHDrmzIQQBjW3vGPxGRTImfezaBGKJislHVKU2OyA";

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(XConstants.SESSION_USER);
		EventManager eventManager = new EventManagerImpl();
		StringBuilder error = new StringBuilder();
		String eventTitle = request.getParameter("eventTitle");
		String description = request.getParameter("eventDescription");
		String start = request.getParameter("eventStart");
		String end = request.getParameter("eventEnd");
		String locationKey = request.getParameter("locationKey");
		System.out.println(locationKey);
		Date dStart = new Date(Long.parseLong(start) + 3600000);
		Date dEnd = new Date(Long.parseLong(end) + 3600000);
		Event event = new Event();
		event.setTitle(eventTitle);
		event.setDescription(description);
		event.setStartTime(dStart);
		event.setEndTime(dEnd);
		if (!locationKey.equals("Select your locations")) event.setLocationKey(KeyFactory.stringToKey(locationKey));
		eventManager.addEvent(user, event);

		UserManager um = new UserManagerImpl();
		try {
			user = um.login(user.getUserName(), user.getPassword());
		} catch (IncorrectNameOrPasswordException e) {
			error.append("Incorrect username Or wrong password !");
			request.setAttribute(XConstants.WRONY_MESSAGE, error.toString());
			RequestDispatcher view = request.getRequestDispatcher("welcome.jsp");
			view.forward(request, response);
		}

		List<Event> events = user.getEvents();
		Event event2 = events.get(events.size() - 1);
		//System.out.println(event2.getLocationKey().toString()+"____");
		JSONObject obj = new JSONObject();
		SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			obj.put("key", KeyFactory.keyToString(event2.getKey()));
			obj.put("title", event2.getTitle());
			obj.put("description", event2.getDescription());
			obj.put("startTime", time.format(event2.getStartTime()));
			obj.put("endTime", time.format(event2.getEndTime()));
			obj.put("allDay", false);
			obj.put("userKey", KeyFactory.keyToString(event2.getUserKey()));
		} catch (JSONException e) {
			// TODO: handle exception
		}
		String authToken = C2DMManager.getAuthToken(ClientLoginURL, AuthTokenParams);
		if (authToken != null) {
			Map<String, String> data = new HashMap<String, String>();
			data.put("data.msg", obj.toString());
			if (C2DMManager.sendPushMessage(C2DMServerURL, user.getRegistrationID(), "1", authToken, data)) {
				System.out.println("Send Successfully");
			} else {
				System.out.println("Send Failed");
			}
		}

		response.setContentType("text/plain");
		response.getWriter().println(KeyFactory.keyToString(event2.getKey()));

	}
}
